<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <style>
            * {
                margin: 0;
                padding: 0;
            }
            .header {
                width: 100%;
                height: 50px;
                background-color: pink;
            }
        </style>
    </head>
    <body>
        <h1>123</h1>
        <h1>123</h1>
        <h1>123</h1>
        <h1>123</h1>
        <h1>123</h1>
        <h1>123</h1>
        <h1>123</h1>
        <h1>123</h1>
        <div class="header"></div>
        <h1>123</h1>
        <h1>123</h1>
        <h1>123</h1>
        <h1>123</h1>
        <h1>123</h1>
        <h1>123</h1>
        <h1>123</h1>
        <h1>123</h1>
        <h1>123</h1>
        <h1>123</h1>
        <h1>123</h1>
        <h1>123</h1>
        <h1>123</h1>
        <h1>123</h1>
        <h1>123</h1>
        <h1>123</h1>
        <h1>123</h1>
        <h1>123</h1>
        <h1>123</h1>
        <h1>123</h1>
        <h1>123</h1>
        <h1>123</h1>
        <h1>123</h1>
        <h1>123</h1>
        <h1>123</h1>
        <h1>123</h1>
        <h1>123</h1>
        <h1>123</h1>
        <script>
            // 获取header元素
            let header = document.querySelector(".header");
            // 获取header的据浏览器的高度，使用offset获取高度方便获取值
            let headerOffsetTop = header.offsetTop;
            window.onscroll = () => {
                // 获取滚动条的滚动距离
                let scrollHeight =
                    document.body.scrollTop ||
                    document.documentElement.scrollTop;
                //滚动条滚动的距离一旦大于获取的高度进行修改属性
                if (scrollHeight >= headerOffsetTop) {
                    header.style.position = "fixed";//悬浮与文档流上
                    header.style.top = "0px";
                } else {
                    header.style.position = "";
                }
            };
        </script>
    </body>
</html>
